package org.tao.lightningmq.nameserver.core;

import org.tao.lightningmq.nameserver.common.CommonCache;
import org.tao.lightningmq.nameserver.event.model.UnRegistryEvent;
import org.tao.lightningmq.nameserver.store.ServiceInstance;

import java.sql.Time;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author lht
 * @date 2025/1/8 - 14:26
 * @description: 无效服务移除任务
 */
public class InValidServiceRemoveTask implements Runnable{
    @Override
    public void run() {
        Map<String, ServiceInstance> serviceInstanceMap = CommonCache.getServiceInstanceManager().getServiceInstanceMap();
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(3);
                long currentTimeMillis = System.currentTimeMillis();
                Iterator<String> iterator = serviceInstanceMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    ServiceInstance serviceInstance = serviceInstanceMap.get(key);
                    if (serviceInstance.getLastHeartBeatTime() == null) {
                        continue;
                    }
                    if (currentTimeMillis - serviceInstance.getLastHeartBeatTime() > 9000) {
                        serviceInstance.getContext().close();
                        iterator.remove();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
